from rest_framework import serializers
from .models import Delivery, DeliveryRoute, DeliveryLog
from orders.serializers import OrderSerializer
from users.serializers import DeliveryStaffSerializer

class DeliveryRouteSerializer(serializers.ModelSerializer):
    class Meta:
        model = DeliveryRoute
        fields = [
            'id', 'delivery', 'start_location', 'end_location',
            'estimated_distance', 'estimated_time',
            'actual_distance', 'actual_time'
        ]
        read_only_fields = ['id']

class DeliveryLogSerializer(serializers.ModelSerializer):
    class Meta:
        model = DeliveryLog
        fields = ['id', 'delivery', 'location', 'status', 'note', 'created_at']
        read_only_fields = ['created_at']

class DeliverySerializer(serializers.ModelSerializer):
    order = OrderSerializer(read_only=True)
    order_id = serializers.IntegerField(write_only=True)
    deliveryman_name = serializers.CharField(source='deliveryman.username', read_only=True)
    delivery_staff_detail = DeliveryStaffSerializer(source='delivery_staff', read_only=True)
    route = DeliveryRouteSerializer(read_only=True)
    logs = DeliveryLogSerializer(many=True, read_only=True)

    class Meta:
        model = Delivery
        fields = [
            'id', 'order', 'order_id', 'deliveryman', 'deliveryman_name',
            'delivery_staff', 'delivery_staff_detail',
            'status', 'pickup_time', 'delivery_time',
            'note', 'route', 'logs',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['created_at', 'updated_at'] 